package com.example.membersteward.util;

import com.example.membersteward.common.CommonResult;
import com.example.membersteward.entity.ExcelTableInfo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

public class ExcelUtils {
    private static final Logger logger = LoggerFactory.getLogger(ExcelUtils.class);

    public static CommonResult generateExcelTemplate(List<ExcelTableInfo> params, String[][] data) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("用户信息");
            // 创建表头样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerFont.setFontHeightInPoints((short) 12);
            headerStyle.setFont(headerFont);
            // 设置背景颜色
            byte[] rgb = new byte[]{(byte) 204, (byte) 204, (byte) 204};
            XSSFColor color = new XSSFColor(rgb, null);
            headerStyle.setFillForegroundColor(color);
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            // 设置边框
            headerStyle.setBorderTop(BorderStyle.THIN);
            headerStyle.setBorderBottom(BorderStyle.THIN);
            headerStyle.setBorderLeft(BorderStyle.THIN);
            headerStyle.setBorderRight(BorderStyle.THIN);

            // 设置表头内容上下和左右居中
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            Row headerRow = sheet.createRow(0);
            headerRow.setHeightInPoints(30);
            for (int i = 0; i < params.size(); i++) {
                ExcelTableInfo excel = params.get(i);
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(excel.getTableName());
                System.out.println(excel.getTableName());
                cell.setCellStyle(headerStyle);
                // 设置列宽，这里可以根据需要调整宽度，乘以 256 是因为 POI 中列宽单位是 1/256 个字符宽度
                sheet.setColumnWidth(i, excel.getColumnWidth() * 256);
                // 设置表头提示信息
                if (BaseUtils.isNotNull(excel.getDescription())) {
                    Drawing<?> drawing = sheet.createDrawingPatriarch();
                    XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, i, 0, i + 1, 1);
                    XSSFComment comment = (XSSFComment) drawing.createCellComment(anchor);
                    comment.setString(workbook.getCreationHelper().createRichTextString(excel.getDescription()));
                    cell.setCellComment(comment);
                }

                if (BaseUtils.isNotNull(excel.getDropdownOptions())) {
                    DataValidationHelper dvHelper = sheet.getDataValidationHelper();
                    DataValidationConstraint dvConstraint = dvHelper.createExplicitListConstraint(excel.getDropdownOptions().toArray(new String[0]));
                    CellRangeAddressList addressList = new CellRangeAddressList(1, 1000, i, i);
                    DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);
                    sheet.addValidationData(validation);
                }
            }
            if (BaseUtils.isNotNull(data)) {
                for (int rowNum = 0; rowNum < data.length; rowNum++) {
                    Row bodyRow = sheet.createRow(rowNum + 1);
                    CellStyle bodyStyle = workbook.createCellStyle();
                    bodyStyle.setBorderTop(BorderStyle.THIN);
                    bodyStyle.setBorderBottom(BorderStyle.THIN);
                    bodyStyle.setBorderLeft(BorderStyle.THIN);
                    bodyStyle.setBorderRight(BorderStyle.THIN);
                    for (int colNum = 0; colNum < data[rowNum].length; colNum++) {
                        Cell cell = bodyRow.createCell(colNum);
                        cell.setCellValue(data[rowNum][colNum]);
                        cell.setCellStyle(bodyStyle);
                    }
                }
            }
            // 将工作簿内容写入字节数组输出流
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                workbook.write(outputStream);
                byte[] bytes = outputStream.toByteArray();
                return CommonResult.success(bytes);
            }
        } catch (IOException e) {
            logger.error("执行异常", e);
            return CommonResult.error("生成excel模板异常");
        }
    }
}
